package com.czy.owner.ui.parity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.CategoryLeftAdapter;
import com.czy.owner.adapter.ClassifyRightAdapter;
import com.czy.owner.adapter.ParityListAdapter;
import com.czy.owner.api.ParityClassifyListApi;
import com.czy.owner.api.ParityListApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.ParityClassifyModel;
import com.czy.owner.entity.ParityModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.czy.owner.global.Constants.REFRESH_DELAY_MILLIS;

/**
 * Created by yang on 2017/10/10.
 * 比价活动
 */

public class ParityActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.et_product_search)
    EditText etProductSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_drawer)
    ImageView ivDrawer;
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView easyRecycleview;
    @BindView(R.id.iv_drawer_back)
    ImageView ivDrawerBack;
    @BindView(R.id.rv_classify_left)
    RecyclerView rvClassifyLeft;
    @BindView(R.id.rv_classify_right)
    RecyclerView rvClassifyRight;
    @BindView(R.id.right_drawer)
    LinearLayout rightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    @BindView(R.id.ll_product_search)
    LinearLayout llProductSearch;
    @BindView(R.id.tv_title)
    TextView toolbarTitle;
    private String goodsName = "";
    private Handler handler = new Handler();
    private int page = 1;
    private ParityListAdapter adapter;

    private CategoryLeftAdapter categoryLeftAdapter;
    private ClassifyRightAdapter classifyRightAdapter;
    private String goodsNam;
    private String categoryId;
    private List<ParityClassifyModel> parityLeftList;
    private List<ParityClassifyModel.NodesBeanX> parityRightList;
    private String goodsActivityId;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_parity;
    }

    @Override
    protected void initInjector() {
        goodsActivityId = getIntent().getStringExtra("goodsActivityId");

    }

    @Override
    protected void initViews() {
        parityLeftList = new ArrayList<>();
        parityRightList = new ArrayList<>();
//        getToolbarTitle().setText("");


        ViewGroup.LayoutParams layoutParams = rightDrawer.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels * 4 / 5;// 设置抽屉出现时的宽度s
        rightDrawer.setLayoutParams(layoutParams);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//侧滑栏关闭手势滑动
        easyRecycleview.setLayoutManager(new LinearLayoutManager(this));
        easyRecycleview.setAdapterWithProgress(adapter = new ParityListAdapter(this));
//        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_order_fragment_recyclerview_divider_decoration));
        easyRecycleview.setEmptyView(R.layout.view_empty_common);
        easyRecycleview.setErrorView(R.layout.view_error_refresh);
        TextView textView = (TextView) easyRecycleview.getEmptyView().findViewById(R.id.tv_empty_content);
        textView.setText("无数据");
        easyRecycleview.getErrorView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        easyRecycleview.setRefreshListener(this);
        easyRecycleview.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                ParityModel.GoodsPageBean.ListBean model = (ParityModel.GoodsPageBean.ListBean) o;
                Intent intent = new Intent(ParityActivity.this, GoodsDetailActivity.class);
                intent.putExtra("goodsId", model.getGoodsId());
                intent.putExtra("mFromType", Constants.GOODSSOURCE_RATE);
                intent.putExtra("mFromTypeId", goodsActivityId);
                startActivity(intent);

            }
        });
        //侧滑左边适配器
        categoryLeftAdapter = new CategoryLeftAdapter(this, 0);
        rvClassifyLeft.setLayoutManager(new LinearLayoutManager(this));
        rvClassifyLeft.setAdapter(categoryLeftAdapter);
        categoryLeftAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {

                categoryLeftAdapter.updateSelectPosition(position);
                setRightAdapter(position);
            }
        });
        //侧滑右边适配器
        classifyRightAdapter = new ClassifyRightAdapter(this);
        GridLayoutManager girdLayoutManager = new GridLayoutManager(this, 2);
        girdLayoutManager.setSpanSizeLookup(classifyRightAdapter.obtainTipSpanSizeLookUp());
        rvClassifyRight.setAdapter(classifyRightAdapter);
        rvClassifyRight.setLayoutManager(girdLayoutManager);
        classifyRightAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {

                ParityClassifyModel.NodesBeanX parityClassifyModel = (ParityClassifyModel.NodesBeanX) o;
//                if (parityClassifyModel.isGroup())
//                    return;
                goodsNam = null;
                categoryId = parityClassifyModel.getCategoryId() + "";
                adapter.clear();
                etProductSearch.setText(null);
                drawerLayout.closeDrawer(rightDrawer);
                onRefresh();
            }
        });
//        rvClassifyRight.setLayoutManager(new LinearLayoutManager(this));
//        rvClassifyRight.setAdapter(classifyRightAdapter);

        etProductSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    categoryId = null;
                    adapter.clear();
                    goodsName = etProductSearch.getText().toString().trim();

                    onRefresh();

                    // do something
                    return true;
                }
                return false;
            }
        });
        etProductSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = s + "";
                if (input.length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.INVISIBLE);
                }
            }
        });
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                llProductSearch.setVisibility(View.GONE);
                toolbarTitle.setText("全部分类");
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                toolbarTitle.setText("");
                llProductSearch.setVisibility(View.VISIBLE);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        onRefresh();
    }

    @Override
    protected void updateViews() {

    }

    //打开侧滑
    public void openRightView() {

        drawerLayout.openDrawer(rightDrawer);
        setLeftAdapter();
    }

    //侧滑左边数据
    private void setLeftAdapter() {
        categoryLeftAdapter.clear();
        categoryLeftAdapter.addAll(parityLeftList);
        if (parityLeftList.size() > 0)
            setRightAdapter(categoryLeftAdapter.getSelectPosition());
    }

    //侧滑右边数据
    private void setRightAdapter(int position) {
        parityRightList.clear();
        classifyRightAdapter.clear();
        List<ParityClassifyModel.NodesBeanX> subs = parityLeftList.get(position).getNodes();//二级
        for (int j = 0; j < subs.size(); j++) {
            ParityClassifyModel.NodesBeanX subsBean = subs.get(j);
            subsBean.setGroup(true);
            parityRightList.add(subsBean);
            for (int k = 0; k < subsBean.getNodes().size(); k++) {
                subsBean.getNodes().get(k).setGroup(false);
                parityRightList.add(subsBean.getNodes().get(k));
            }

        }

        classifyRightAdapter.addAll(parityRightList);
    }

    //获取商品分类列表
    private void getDataClassify() {
        final ParityClassifyListApi parityListApi = new ParityClassifyListApi(new HttpOnNextListener<List<ParityClassifyModel>>() {
            @Override
            public void onNext(List<ParityClassifyModel> model) {
                parityLeftList.addAll(model);
                openRightView();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

                MyLog.e("hep", e.getMessage() + "----");
                e.printStackTrace();


            }
        }, this);

        parityListApi.setGoodsActivityId(goodsActivityId);
        parityListApi.setSession(UserHelper.getInstance().getSession(this));
        HttpManager.getInstance().doHttpDeal(parityListApi);
    }

    //获取商品列表
    private void getData(final boolean isfirst) {
        ParityListApi parityListApi = new ParityListApi(new HttpOnNextListener<ParityModel>() {
            @Override
            public void onNext(ParityModel model) {
                if (model.getGoodsPage().getList() != null) {

                    if (isfirst) {
                        adapter.clear();

                    }
                    if (model.getGoodsPage().getList().size() < 9) {
                        adapter.stopMore();

                    }
                    adapter.addAll(model.getGoodsPage().getList());
                } else {
                    adapter.addAll(model.getGoodsPage().getList());
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                if (isfirst) {
                    easyRecycleview.showError();
                }

            }
        }, this);
        parityListApi.setGoodsActivityId(goodsActivityId + "");
        parityListApi.setSize(10 + "");
        parityListApi.setSession(UserHelper.getInstance().getSession(this));
        parityListApi.setGoodsName(etProductSearch.getText().toString().trim());
        parityListApi.setPage(page + "");
        parityListApi.setCategoryId(categoryId);
        parityListApi.setStoreId(SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        HttpManager.getInstance().doHttpDeal(parityListApi);
    }

    @OnClick({R.id.iv_drawer, R.id.iv_clear, R.id.iv_drawer_back, R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_drawer:
                if (parityLeftList.size() > 0) {
                    openRightView();
                } else {
                    getDataClassify();
                }
                break;
            case R.id.iv_clear:
                etProductSearch.setText("");
                goodsName = "";
                break;
            case R.id.iv_drawer_back:
                drawerLayout.closeDrawer(rightDrawer, true);
                break;
            case R.id.img_back:
                finish();
                break;

        }
    }

    @Override
    public void onRefresh() {
        easyRecycleview.showProgress();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(ParityActivity.this)) {
                    adapter.pauseMore();
                    easyRecycleview.showError();
                    return;
                }

                page = 1;
                getData(true);
            }
        }, REFRESH_DELAY_MILLIS);
    }

    @Override
    public void onLoadMore() {
        //刷新
        if (!PhoneUtils.isNetworkConnected(ParityActivity.this)) {
            if (adapter != null)
                adapter.pauseMore();
            return;
        }
        page++;
        getData(false);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
